package cn.com.jslh.boarpro.main.presenter;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.BuildConfig;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import cn.com.jslh.boarpro.main.LoginActivity;
import cn.com.jslh.boarpro.main.entity.UpAppEntity;
import cn.com.jslh.boarpro.main.model.UpDataAppModelImpl;
import cn.com.jslh.boarpro.util.AbToastUtil;
import cn.com.jslh.boarpro.util.NetBean;
import io.reactivex.functions.Consumer;

/**
 * Created by lenovo on 2018/4/7.
 */

public class UpDataAppPresenterImpl {
    private Context context;
    private UpDataAppModelImpl model;

    public UpDataAppPresenterImpl(Context context) {
        this.context = context;
        model=new UpDataAppModelImpl(context);
    }


    public void getData(){
        final UpAppEntity app=new UpAppEntity();
        app.setAppcode("pigapp");
        app.setType("1");
        String js= JSON.toJSONString(app);
        Log.d("打印json",js);
        model.initData(js, new NetBean.NetSuccessListener() {
            @Override
            public void Success(JSONArray jsonArray) throws JSONException {

            }

            @Override
            public void Success(JSONObject resJson) throws JSONException {
                super.Success(resJson);
                Log.d("strJson",resJson.toString()+"zxx");
                final String version=resJson.getString("version");
                final String url=resJson.getString("url");
                if(!version.equals(AppUtils.getAppVersionName())){
                    //下载新的版本
                    Toast.makeText(context,"发现新版本",Toast.LENGTH_SHORT).show();
                    new RxPermissions((Activity) context)
                            .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            .subscribe(new Consumer<Boolean>() {
                                           @Override
                                           public void accept(Boolean aBoolean) throws Exception {
                                               if(aBoolean){
                                                   choseTodownload(context,url);
                                               }else {

                                               }
                                           }
                                       });

                }else {
                    Intent intent=new Intent(context,LoginActivity.class);
                    context.startActivity(intent);
                }
            }


        }, new NetBean.NetFaildListener() {
            @Override
            public void Faild(String str) {
                Log.d("fail",str+"zz");
            }
        });
    }

    /**
     * 选择是否更新。
     */
    public  void choseTodownload(final Context context, final String verUrl) {
        new AlertDialog.Builder(context)
                .setTitle("新版本提示")
//                .setMessage(verDesc)
                .setCancelable(false)
                .setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        downloadApk(context,verUrl);
                    }
                }).show();

    }

    public  void downloadApk(final Context context, String verUrl) {
        final ProgressDialog progressDialog = new ProgressDialog(context, ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("下载中....");
        progressDialog.setCancelable(false);
        OkGo.<File>get(verUrl)
                .tag(verUrl)
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new FileCallback() {
                    @Override
                    public void onStart(Request<File, ? extends Request> request) {
                        progressDialog.show();
                    }

                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<File> response) {
                        if (response.isSuccessful()) {
                            choseToinstallApk(context, response.body());
                        }
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        AbToastUtil.showToast(context, (int) (progress.fraction * 100) + "%", Toast.LENGTH_LONG);
                        progressDialog.setMax((int) progress.totalSize);
                        progressDialog.setProgress((int) progress.currentSize);
                    }

                    @Override
                    public void onFinish() {
                        progressDialog.dismiss();
                    }
                });

    }

    //安装应用确认
    public  void choseToinstallApk(final Context context, final File apkFile) {
        installApk(context, apkFile);
    }

    //应用安装
    public static void installApk(final Context context, File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Log.d("filePath",apkFile.getAbsolutePath());
        Log.d("fileSize",apkFile.exists()+"zxx");
//        File apkFile=new File("file://"+file.getAbsolutePath());
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, "cn.com.jslh.boarpro.fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }




}
